package com.hfy.pcberpbackend.controller;

import com.hfy.pcberpbackend.entity.Supplier;
import com.hfy.pcberpbackend.service.SupplierService;
import com.hfy.pcberpbackend.dto.SupplierQueryDTO;
import com.hfy.pcberpbackend.dto.BatchDeleteDTO;
import com.hfy.pcberpbackend.common.Result;
import com.hfy.pcberpbackend.common.PageResult;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;
import java.util.HashMap;

/**
 * 供应商Controller
 */
@Slf4j
@RestController
@RequestMapping("/api/suppliers")
@RequiredArgsConstructor
@Validated
public class SupplierController {
    
    private final SupplierService supplierService;
    
    /**
     * 获取供应商列表
     */
    @GetMapping
    public Result<PageResult<Supplier>> getSupplierList(SupplierQueryDTO query) {
        log.info("获取供应商列表，查询条件：{}", query);
        
        try {
            PageResult<Supplier> result = supplierService.getSupplierPage(query);
            return Result.success("获取成功", result);
        } catch (Exception e) {
            log.error("获取供应商列表失败", e);
            return Result.error("获取供应商列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 根据ID获取供应商详情
     */
    @GetMapping("/{id}")
    public Result<Supplier> getSupplierById(@PathVariable Long id) {
        log.info("根据ID获取供应商详情，ID：{}", id);
        
        try {
            Supplier supplier = supplierService.getSupplierById(id);
            return Result.success("获取成功", supplier);
        } catch (RuntimeException e) {
            log.error("获取供应商详情失败", e);
            return Result.notFound(e.getMessage());
        } catch (Exception e) {
            log.error("获取供应商详情失败", e);
            return Result.error("获取供应商详情失败：" + e.getMessage());
        }
    }
    
    /**
     * 新增供应商
     */
    @PostMapping
    public Result<Map<String, Long>> createSupplier(@Valid @RequestBody Supplier supplier) {
        log.info("新增供应商：{}", supplier);
        
        try {
            Long id = supplierService.createSupplier(supplier);
            Map<String, Long> result = new HashMap<>();
            result.put("id", id);
            return Result.success("新增成功", result);
        } catch (RuntimeException e) {
            log.error("新增供应商失败", e);
            return Result.badRequest(e.getMessage());
        } catch (Exception e) {
            log.error("新增供应商失败", e);
            return Result.error("新增供应商失败：" + e.getMessage());
        }
    }
    
    /**
     * 更新供应商信息
     */
    @PutMapping("/{id}")
    public Result<Void> updateSupplier(@PathVariable Long id, @Valid @RequestBody Supplier supplier) {
        log.info("更新供应商信息，ID：{}，数据：{}", id, supplier);
        
        try {
            supplierService.updateSupplier(id, supplier);
            return Result.success("更新成功");
        } catch (RuntimeException e) {
            log.error("更新供应商失败", e);
            return Result.badRequest(e.getMessage());
        } catch (Exception e) {
            log.error("更新供应商失败", e);
            return Result.error("更新供应商失败：" + e.getMessage());
        }
    }
    
    /**
     * 删除供应商
     */
    @DeleteMapping("/{id}")
    public Result<Void> deleteSupplier(@PathVariable Long id) {
        log.info("删除供应商，ID：{}", id);
        
        try {
            supplierService.deleteSupplier(id);
            return Result.success("删除成功");
        } catch (RuntimeException e) {
            log.error("删除供应商失败", e);
            return Result.badRequest(e.getMessage());
        } catch (Exception e) {
            log.error("删除供应商失败", e);
            return Result.error("删除供应商失败：" + e.getMessage());
        }
    }
    
    /**
     * 批量删除供应商
     */
    @DeleteMapping("/batch")
    public Result<Void> batchDeleteSuppliers(@Valid @RequestBody BatchDeleteDTO batchDeleteDTO) {
        log.info("批量删除供应商，IDs：{}", batchDeleteDTO.getIds());
        
        try {
            supplierService.batchDeleteSuppliers(batchDeleteDTO.getIds());
            return Result.success("批量删除成功");
        } catch (RuntimeException e) {
            log.error("批量删除供应商失败", e);
            return Result.badRequest(e.getMessage());
        } catch (Exception e) {
            log.error("批量删除供应商失败", e);
            return Result.error("批量删除供应商失败：" + e.getMessage());
        }
    }
    
    /**
     * 导出供应商Excel
     */
    @GetMapping("/export")
    public Result<String> exportSuppliers(SupplierQueryDTO query) {
        log.info("导出供应商Excel，查询条件：{}", query);
        
        try {
            // TODO: 实现Excel导出功能
            return Result.success("导出功能开发中");
        } catch (Exception e) {
            log.error("导出供应商Excel失败", e);
            return Result.error("导出供应商Excel失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取供应商类型选项
     */
    @GetMapping("/types")
    public Result<List<Map<String, String>>> getSupplierTypes() {
        log.info("获取供应商类型选项");
        
        try {
            List<Map<String, String>> types = supplierService.getSupplierTypes();
            return Result.success("获取成功", types);
        } catch (Exception e) {
            log.error("获取供应商类型选项失败", e);
            return Result.error("获取供应商类型选项失败：" + e.getMessage());
        }
    }
    
    /**
     * 检查供应商代码唯一性
     */
    @GetMapping("/check-code")
    public Result<Map<String, Boolean>> checkSupplierCode(
            @RequestParam String supplierCode,
            @RequestParam(required = false) Long excludeId) {
        log.info("检查供应商代码唯一性，代码：{}，排除ID：{}", supplierCode, excludeId);
        
        try {
            boolean exists = supplierService.isSupplierCodeExists(supplierCode, excludeId);
            Map<String, Boolean> result = new HashMap<>();
            result.put("exists", exists);
            return Result.success("检查完成", result);
        } catch (Exception e) {
            log.error("检查供应商代码唯一性失败", e);
            return Result.error("检查供应商代码唯一性失败：" + e.getMessage());
        }
    }
} 